package com.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.common.contant.RestResponse;
import com.common.exception.TaoExceptionEnum;
import com.common.utils.BeanHelper;
import com.dao.mapper.TbSpecGroupMapper;
import com.dao.mapper.TbSpecParamMapper;
import com.dto.TbSpecGroupDTO;
import com.dto.TbSpecParamDTO;
import com.entity.TbSpecGroup;
import com.entity.TbSpecParam;
import com.service.SpecificationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @Author: sijunqiang
 * @Date: 2020/6/3 11:27
 * @Description:
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SpecificationServiceImpl implements SpecificationService {


    private final TbSpecGroupMapper tbSpecGroupMapper;

    private final TbSpecParamMapper tbSpecParamMapper;


    /**
     * 根据商品分类的id 查询出对应的规格组列表
     */
    @Override
    public RestResponse queryGroupInfoByCategoryId(Long id) {

        // 根据条件查询
        TbSpecGroup tbSpecGroup = new TbSpecGroup();
        tbSpecGroup.setCid(id);
        Optional<List<TbSpecGroup>> optional = Optional.ofNullable(tbSpecGroupMapper.select(tbSpecGroup));
        if (!optional.isPresent()) return RestResponse.error(TaoExceptionEnum.BRAND_NOT_FOUND);

        // 转换响应数据
        List<TbSpecGroup> tbSpecGroupList = optional.get();
        List<TbSpecGroupDTO> tbSpecGroupDTOS = BeanHelper.copyWithCollection(tbSpecGroupList, TbSpecGroupDTO.class);
        log.info("<<<结束:根据商品分类的id:[{}],查询出对应的规格组列表:[{}]<<<", id, JSONObject.toJSONString(tbSpecGroupDTOS));
        return RestResponse.success(tbSpecGroupDTOS);

    }

    /**
     * 根据规格组的id 查询规格参数的列表
     */
    @Override
    public RestResponse querySpecParams(Long gid) {

        // 根据条件查询
        TbSpecParam tbSpecParam = new TbSpecParam();
        tbSpecParam.setGroupId(gid);
        Optional<List<TbSpecParam>> optional = Optional.ofNullable(tbSpecParamMapper.select(tbSpecParam));
        if (!optional.isPresent()) return RestResponse.error(TaoExceptionEnum.SPEC_NOT_FOUND);

        // 转换响应数据
        List<TbSpecParam> tbSpecParamList = optional.get();
        log.info("<<<结束: 根据规格组的id:[{}],查询规格参数的列表:[{}]", gid, JSONObject.toJSONString(tbSpecParamList));
        List<TbSpecParamDTO> tbSpecParamDTOS = BeanHelper.copyWithCollection(tbSpecParamList, TbSpecParamDTO.class);
        return RestResponse.success(tbSpecParamDTOS);

    }
}
